/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.aggregator.controller;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.ourgrid.aggregator.AggregatorConstants;
import org.ourgrid.aggregator.dao.AggregatorDAO;
import org.ourgrid.common.interfaces.CommunityStatusProvider;

import br.edu.ufcg.lsd.commune.api.FailureNotification;
import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.api.RecoveryNotification;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;

/**
 * Implements actions when the Community Status Provider recovers or fails.
 */
public class CommunityStatusProviderNotificationController  {

	private ServiceManager serviceManager;

	@SuppressWarnings("unused")
	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	
	/**
	 * 
	 * @param monitorable The DiscoveryService that has failed.
	 * @param deploymentID The DeploymentID of the DiscoveryService that has failed.
	 */
	
	/**
	 * Notifies the Community Status Provider fail.
	 * @param monitorable
	 */
	@FailureNotification
	public void doNotifyFailure(CommunityStatusProvider monitorable) {
		AggregatorDAO dao = serviceManager.getDAO(AggregatorDAO.class);
		dao.setCommunityStatusProvider(null);
		dao.getAdvertActionFuture().cancel(true);
	}
	
	/**
	 * Notifies the Community Status Provider recovery.
	 */
	@RecoveryNotification
	public void doNotifyRecovery(CommunityStatusProvider commStatusProvider) {
		AggregatorDAO dao = serviceManager.getDAO(AggregatorDAO.class);
		dao.setCommunityStatusProvider(commStatusProvider);
		
		Future<?> advertActionFuture = serviceManager.scheduleActionWithFixedDelay(
				AggregatorConstants.GET_PEER_STATUS_PROVIDER_ACTION_NAME, 
				0, AggregatorConstants.GET_PEER_STATUS_PROVIDER_ACTION_DELAY, 
				TimeUnit.SECONDS);
		
		dao.setAdvertActionFuture(advertActionFuture);

	}
	
}
